package cc.linker.steplink.crm.merchant.service.impl;

import cc.linker.steplink.crm.commons.model.PcUserInfo;
import cc.linker.steplink.crm.commons.service.CommonsService;
import cc.linker.steplink.crm.commons.utils.NumberUtils;
import cc.linker.steplink.crm.merchant.dao.acs.WithdrawDao;
import cc.linker.steplink.crm.merchant.service.acs.WithdrawService;
import cc.linker.steplink.crm.merchanth5.service.acs.PurchaseProcessService;
import cc.linker.steplink.crm.response.GlobalException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class WithdrawServiceImpl implements WithdrawService {
    @Autowired
    private WithdrawDao withdrawDao;
    @Autowired
    private CommonsService commonsService;
    @Autowired
    private PurchaseProcessService purchaseProcessService;

    @Override
    public String findCustomerId(String casUserId) {
        return withdrawDao.findCustomerId(casUserId);
    }

    @Override
    public Map<String, String> checkMoney(String customerId) {
        return withdrawDao.checkMoney(customerId);
    }

    @Override
    public String findBankStatus(String customerId) {
        return withdrawDao.findBankStatus(customerId);
    }

    @Override
    public List<Map<String, Object>> withDrawList(Map<String, Object> params) {
        List<Map<String, Object>> result = withdrawDao.withDrawList(params);
        result.forEach(x -> {
            x.put("receiveAmount", NumberUtils.fenToYuan(Long.valueOf(x.get("receiveAmount").toString())));
        });
        return result;
    }

    @Override
    public void export(Map<String, Object> params, HttpServletResponse response) throws Exception {
        // 提现人 手机号 金额 到账账户 状态 时间
        String[] title = {"提现人", "手机号", "金额", "到账账户", "开户行", "状态", "时间"};
        String fileName = "";
        if(StringUtils.isEmpty(params.get("startTime")) || StringUtils.isEmpty(params.get("endTime"))){
            fileName = "提现记录";
        }else{
            fileName = "提现记录(" + params.get("startTime").toString().substring(0,10) + "-" + params.get("endTime").toString().substring(0,10) + ")";
        }
        String[] strings = {"name", "phone", "receiveAmount", "account", "branchName","status", "createTime"};
        List<Map<String, Object>> list = withdrawDao.withDrawList(params);
        for (int i = 0; i < list.size(); i++) {
            String account = StringUtils.isEmpty(list.get(i).get("bankName"))?"":list.get(i).get("bankName").toString()
                    + list.get(i).get("bankAccountNumber").toString();
            list.get(i).put("account", account);
            list.get(i).put("receiveAmount", NumberUtils.fenToYuan(Long.valueOf(list.get(i).get("receiveAmount").toString())));
            list.get(i).put("createTime",list.get(i).get("createTime").toString().substring(0,19));
            list.get(i).remove("bankName");
            list.get(i).remove("bankAccountNumber");
        }
        commonsService.excelDownload(list, strings, title, fileName, response);
    }

    @Override
    public void checkWithDraw(Map<String, Object> params) throws Exception {
        Integer status = Integer.parseInt(params.getOrDefault("status", 0).toString());
        if (status != 2 && status != 3) {
            throw GlobalException.build("审核参数错误！");
        }
        // 更新提现记录状态
        withdrawDao.checkWithDraw(params);

        // 若失败 将金额打回
        if (status == 3) {
            String withDrawId = params.get("withDrawId").toString();
            List<String> withDrawIds = Arrays.asList(withDrawId.split(","));
            withDrawIds.forEach(x -> {
                Map<String, Object> tradeRecord = withdrawDao.getTradeByWithDraw(x);
                Map<String, Object> drawRecord = withdrawDao.getDrawRecord(x);

                //增加 余额
                Map<String, Object> temp = new HashMap<>();
                temp.put("customerId", drawRecord.get("customerId"));
                temp.put("amount", drawRecord.get("totalAmount"));
                //判断小b还是h5用户不同的表
                temp.put("customerType", drawRecord.get("customerType"));
                withdrawDao.updateBalance(temp);

                //记录账单
                Object payUser = tradeRecord.get("receiveUser");
                tradeRecord.put("receiveUser", tradeRecord.get("payUser"));
                tradeRecord.put("payUser", payUser);
                Long reciveAccountBalance = withdrawDao.getBalance(temp);
                tradeRecord.put("reciveAccountBalance", reciveAccountBalance);
                Object receive = tradeRecord.get("payment");
                tradeRecord.put("payment", tradeRecord.get("receive"));
                tradeRecord.put("receive", receive);
                tradeRecord.put("amount", drawRecord.get("totalAmount"));
                tradeRecord.put("type", 12);
                Object payRole = tradeRecord.get("receiveRole");
                tradeRecord.put("receiveRole", tradeRecord.get("payRole"));
                tradeRecord.put("payRole", payRole);
                String busiSn = purchaseProcessService.generateBusiSn(12, (String) temp.get("customerId"));
                tradeRecord.put("busiSn", busiSn);
                withdrawDao.addTrade(tradeRecord);
            });
        }
    }

    @Override
    public Map<String, Object> getWithdrawInfo(PcUserInfo userinfo) {
        Boolean ifSales = userinfo.getSaler();
        String orgId = userinfo.getOrgId();
        Map<String, Object> orgSet = withdrawDao.getOrgSetByOrgId(orgId);
        if (orgSet == null) {
            throw GlobalException.build("请先设置支付配置");
        }
        if (ifSales) {
            // 小b
            String adminId = userinfo.getAdminId();
            Long balance = withdrawDao.getBalanceByAdminId(adminId);
            orgSet.put("balance", balance);
        }
        Long balance = (Long) orgSet.get("balance");
        double v = balance.doubleValue() / 100;
        String s = new BigDecimal(v).setScale(2, BigDecimal.ROUND_HALF_EVEN).toString();
        orgSet.put("balance", s);
        Long withdrawLimit = (Long) orgSet.get("withdrawLimit");
        double v2 = withdrawLimit.doubleValue() / 100;
        String s2 = new BigDecimal(v2).setScale(2, BigDecimal.ROUND_HALF_EVEN).toString();
        orgSet.put("withdrawLimit", s2);

        Integer withdrawTakeType = (Integer) orgSet.get("withdrawTakeType");
        if (withdrawTakeType == null) {
            throw GlobalException.build("支付配置未设置提现抽成类型");
        } else if (withdrawTakeType == 1) {
            Double withdrawRate = Double.valueOf((String) orgSet.get("withdrawRate"));
            if (withdrawRate == null) {
                withdrawRate = 0.0;
            }
            orgSet.put("withdraw", withdrawRate + "%");
        } else if (withdrawTakeType == 2) {
            Long withdrawCost = (Long) orgSet.get("withdrawCost");
            if (withdrawCost == null) {
                withdrawCost = 0L;
            }
            double v1 = withdrawCost.doubleValue() / 100;
            String s1 = new BigDecimal(v1).setScale(2, BigDecimal.ROUND_HALF_EVEN).toString();
            orgSet.put("withdraw", s1 + "元");
        }
        return orgSet;
    }
}
